package com.xilihui.xlh.business.activitys.store;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xilihui.xlh.R;
import com.xilihui.xlh.business.activitys.ChecklistActivity;
import com.xilihui.xlh.business.dialogs.StoreBuyDialog;
import com.xilihui.xlh.business.entities.CheckEntity;
import com.xilihui.xlh.business.entities.RecommendGoodEntity;
import com.xilihui.xlh.business.entities.StoreCartListEntity;
import com.xilihui.xlh.business.entities.StoreDetailsEntity;
import com.xilihui.xlh.business.requests.MyAppointmentRequest;
import com.xilihui.xlh.business.requests.StoreRequest;
import com.xilihui.xlh.component.recyclerview.BaseAdapter;
import com.xilihui.xlh.component.recyclerview.BaseViewHolder;
import com.xilihui.xlh.component.recyclerview.LinearLayoutColorDivider;
import com.xilihui.xlh.constant.UrlConst;
import com.xilihui.xlh.core.app.BaseEntity;
import com.xilihui.xlh.core.app.ToolBaseCompatActivity;
import com.xilihui.xlh.core.exception.DefaultExceptionListener;
import com.xilihui.xlh.core.exception.ExceptionManager;
import com.xilihui.xlh.core.http.DoTransform;
import com.xilihui.xlh.core.http.HttpSubscriber;
import com.xilihui.xlh.core.util.ToastUtil;
import com.xilihui.xlh.core.util.YEventBuses;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/9/5.
 */

public class CartActivity extends ToolBaseCompatActivity implements OnRefreshListener, OnLoadMoreListener, View.OnClickListener {
    
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.recyclerview)
    XRecyclerView recyclerView;
    @BindView(R.id.rl_jiesuan)
    RelativeLayout rl_jiesuan;

    @BindView(R.id.cb_allSelect)
    CheckBox cb_all;
    @BindView(R.id.tv_totalNum)
    TextView tv_totalNum;
    @BindView(R.id.tv_jiesuan)
    TextView tv_jiesuan;
    
    RecyclerView recyclerViewHead;
    boolean isNull = true;
    
    ExceptionManager exceptionManager;
   
    
    int page = 1;
    BaseAdapter<StoreCartListEntity.GoodsBean> goodAdapter;
    ArrayList<StoreCartListEntity.GoodsBean> goods = new ArrayList<>();
    
    BaseAdapter<RecommendGoodEntity.GoodsBean> baseAdapter;
    ArrayList<RecommendGoodEntity.GoodsBean> data = new ArrayList<>();

    boolean isManage = true;
    boolean isCheckAll = true;

    int qingdannum = 0;//清单数量
    float jiesuanJiner = 0;//结算金额
    int jiesuanNum = 0;//结算商品数量
    
    @OnClick(R.id.iv_toolbar_left)
    public void back(){
        finish();
    }

    @OnClick(R.id.tv_toolbar_right)
    public void manage() {
        if (isManage) {
            setToolRightText("完成");
            tv_totalNum.setVisibility(View.INVISIBLE);
            tv_jiesuan.setText("删除");
            isManage = false;
        } else {
            setToolRightText("管理");
            tv_totalNum.setVisibility(View.VISIBLE);
            tv_jiesuan.setText("结算(3)");
            isManage = true;
            handle();
        }
    }
    
    @Override
    public int getLayout() {
        return R.layout.activity_cart;
    }

    @Override
    public String initTitle() {
        return null;
    }
    
    @Override
    public void initUI(@Nullable Bundle savedInstanceState) {
        setToolTitle("购物车");
        
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
        recyclerView.setLoadingMoreEnabled(false);
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.view_line,
                R.dimen.divider_space,LinearLayout.VERTICAL));
        
       
        initHeadView();
        initRecyclerView();

        cb_all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                String select = "";
                if (b) {
                    select = "1";
                } else {
                    select = "0";
                }

                if(!isCheckAll){
                    isCheckAll = true;
                    return;
                }else {
                    isCheckAll = true;
                }

                final String finalSelect = select;
                StoreRequest.selectAll(CartActivity.this,finalSelect)
                        .compose(DoTransform.<BaseEntity>applyScheduler(CartActivity.this, false))
                        .subscribe(new HttpSubscriber<BaseEntity>(CartActivity.this) {
                            @Override
                            protected void onSuccess(BaseEntity entity) {
                                int num = goods.size();
                                if (num > 0) {
                                    for (int i = 0; i < num; i++) {
                                        goods.get(i).setSelected(finalSelect);
                                    }
                                    goodAdapter.setList(goods);
                                    handle();
                                }
                            }

                            @Override
                            protected void onFail(String msg) {
                                ToastUtil.toastShortNegative(msg);
                            }
                        });
                
            }

        });
        
        tv_jiesuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                
                if(isManage){
                    Intent intent = new Intent(CartActivity.this,ConfirmOrderActivity.class);
                    intent.putExtra("type",1);
                    startActivity(intent); 
                }else {
                    StoreRequest.deleteCart(CartActivity.this)
                            .compose(DoTransform.<BaseEntity>applyScheduler(CartActivity.this,true))
                            .compose(CartActivity.this.<BaseEntity>bindToLifecycle())
                            .subscribe(new HttpSubscriber<BaseEntity>(CartActivity.this) {
                                @Override
                                protected void onSuccess(BaseEntity entity) {
                                    ToastUtil.toastShortPositive(entity.getMsg());
                                    page = 1;
                                    getData(false);
                                    getRecommendGoods(false);
                                }

                                @Override
                                protected void onFail(String msg) {
                                    ToastUtil.toastShortNegative(msg);
                                }
                            });
                }
                
                
            }
        });
        
        
    }
    
    public void initHeadView(){
        
        
        View view = LayoutInflater.from(CartActivity.this).inflate(R.layout.reyceler_item_cart_null_head,null);
        recyclerViewHead = (RecyclerView)view.findViewById(R.id.recyclerview);
        recyclerViewHead.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewHead.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.tv_color_fff,
                R.dimen.divider_space,LinearLayout.VERTICAL));
        
        exceptionManager = new ExceptionManager(recyclerViewHead,new DefaultExceptionListener(this)){
            @Override
            protected int getEmptyView() {
                return R.layout.empty_shop;
            }
        };
        
        goodAdapter = new BaseAdapter<StoreCartListEntity.GoodsBean>(this,goods) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_checklist;
            }

            @Override
            protected void getView(final BaseViewHolder holder, final StoreCartListEntity.GoodsBean entity, final int position) {
                
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.iv_shop_img);
                simpleDraweeView.setImageURI(UrlConst.baseUrl()+entity.getOriginal_img());
                
                holder.setText(R.id.tv_shopName,entity.getGoods_name());
                holder.setText(R.id.tv_model,entity.getSpec_key_name());
                holder.setText(R.id.tv_price,"￥"+entity.getGoods_price());

                final int[] good_num = {Integer.valueOf(entity.getGoods_num())};
                final TextView textView = (TextView)holder.getView(R.id.tv_num);
                textView.setText(good_num[0] +"");
                
                
                final String id = entity.getId();
                holder.setOnClickListener(R.id.tv_model, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        StoreRequest.goodsInfo(CartActivity.this,entity.getId())
                                .compose(DoTransform.<StoreDetailsEntity>applyScheduler(CartActivity.this,true))
                                .subscribe(new HttpSubscriber<StoreDetailsEntity>(CartActivity.this) {
                                    @Override
                                    protected void onSuccess(StoreDetailsEntity entity) {
                                        String goods_id = entity.getGoods_spec().getDefault_info().getGoods_id();
                                        int num = Integer.valueOf(textView.getText().toString());
                                        StoreBuyDialog buyDialog = new StoreBuyDialog(CartActivity.this,entity,goods_id,id,num,3);
                                        buyDialog.show();
                                    }
                                    
                                    @Override
                                    protected void onFail(String msg) {
                                        ToastUtil.toastShortNegative(msg);
                                    }
                                });
                    }
                });
                
                holder.setOnClickListener(R.id.iv_jian, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        
                            int good_num = entity.getGoods_num();
                            if(good_num>1){
                                good_num = good_num -1;
                            }
                            final int finalGood_num = good_num;
                            StoreRequest.updateCart(CartActivity.this,entity.getId(),"",finalGood_num +"")
                                    .compose(DoTransform.<BaseEntity>applyScheduler((FragmentActivity)CartActivity.this,true))
                                    .compose(CartActivity.this.<BaseEntity>bindToLifecycle())
                                    .subscribe(new HttpSubscriber<BaseEntity>(CartActivity.this) {
                                        @Override
                                        protected void onSuccess(BaseEntity ent) {
                                            entity.setGoods_num(finalGood_num);
                                            holder.setText(R.id.tv_num, finalGood_num+ "");
                                            handle();
                                        }

                                        @Override
                                        protected void onFail(String msg) {
                                            ToastUtil.toastShortNegative(msg);
                                        }
                                    });
                            
                            
                    }
                });
                
                
                holder.setOnClickListener(R.id.iv_jia, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int good_num = entity.getGoods_num();
                        good_num = good_num + 1;
                        final int finalGood_num = good_num;
                        StoreRequest.updateCart(CartActivity.this,entity.getId()+"","",finalGood_num+"")
                                .compose(DoTransform.<BaseEntity>applyScheduler(CartActivity.this,true))
                                .compose(CartActivity.this.<BaseEntity>bindToLifecycle())
                                .subscribe(new HttpSubscriber<BaseEntity>(CartActivity.this) {
                                    @Override
                                    protected void onSuccess(BaseEntity ent) {
                                        entity.setGoods_num(finalGood_num);
                                        holder.setText(R.id.tv_num, finalGood_num+ "");
                                        handle();
                                    }

                                    @Override
                                    protected void onFail(String msg) {
                                        ToastUtil.toastShortNegative(msg);
                                    }
                                });
                    }
                });


                CheckBox checkBox = (CheckBox) holder.getView(R.id.cb_select);
                if (entity.getSelected().equals("1")) {
                    checkBox.setChecked(true);
                } else {
                    checkBox.setChecked(false);
                }
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        String select = "";
                        if (b) {
                            select = "1";
                        } else {
                            select = "0";
                        }

                        final String finalSelect = select;
                        StoreRequest.selectOne(CartActivity.this,entity.getId(),select)
                                .compose(DoTransform.<BaseEntity>applyScheduler((FragmentActivity)CartActivity.this,false))
                                .subscribe(new HttpSubscriber<BaseEntity>(CartActivity.this) {
                                    @Override
                                    protected void onSuccess(BaseEntity entity) {
                                        goods.get(position).setSelected(finalSelect);
                                        handle();
                                    }

                                    @Override
                                    protected void onFail(String msg) {
                                        
                                    }
                                });
                    }

                });
                
                
            }
        };
        
        recyclerViewHead.setAdapter(goodAdapter);
        recyclerView.addHeaderView(view);
        
    }
    
    public void initRecyclerView(){
        GridLayoutManager gridLayoutManager = new GridLayoutManager(CartActivity.this,2);
        recyclerView.setLayoutManager(gridLayoutManager);
        
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.tv_color_fff,R.dimen.divider_space,
                LinearLayout.VERTICAL));
        recyclerView.addItemDecoration(new LinearLayoutColorDivider(getResources(),R.color.tv_color_fff,R.dimen.divider_space,
                LinearLayout.HORIZONTAL));
        
        baseAdapter = new BaseAdapter<RecommendGoodEntity.GoodsBean>(this,data) {
            @Override
            protected int setLayoutId() {
                return R.layout.recycler_item_shop_good;
            }

            @Override
            protected void getView(BaseViewHolder holder, final RecommendGoodEntity.GoodsBean entity, int position) {
                
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView)holder.getView(R.id.sdv);
                simpleDraweeView.setImageURI(UrlConst.baseUrl() + entity.getOriginal_img());
                
                holder.setText(R.id.tv_title,entity.getGoods_name());
                holder.setText(R.id.tv_price,"￥"+entity.getShop_price());
                holder.setText(R.id.tv_num,"售出"+entity.getSales_sum()+"件");
                                
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(CartActivity.this, StoreGoodDetailsActivity.class);
                        intent.putExtra("goods_id",entity.getGoods_id());
                        startActivity(intent);
                        finish();
                    }
                });
               
            }
        };
        
        recyclerView.setAdapter(baseAdapter);
        baseAdapter.setAnimationsLocked(true);
        
        getData(true);
        getRecommendGoods(true);
        
    }

    @Override
    public void initData() {
        
    }
    
    public void getData(boolean isLoading){
        StoreRequest.cartList(CartActivity.this)
                .compose(DoTransform.<StoreCartListEntity>applyScheduler(this,isLoading))
                .compose(this.<StoreCartListEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<StoreCartListEntity>(this) {
                    @Override
                    protected void onSuccess(StoreCartListEntity entity) {
                        goods.clear();
                        goods.addAll(entity.getGoods());

                        if(goods.size()>0){
                            exceptionManager.hide();
                            rl_jiesuan.setVisibility(View.VISIBLE);
                            setToolRightText("管理");
                        }else {
                            exceptionManager.showEmpty();
                            rl_jiesuan.setVisibility(View.GONE);
                            setToolRightText("");
                        }

                        boolean isall = true;
                        qingdannum = goods.size();
                        setToolTitle("清单(" + qingdannum + ")");

                        if (goods.size() > 0) {
                            for (int i = 0; i < goods.size(); i++) {
                                if (goods.get(i).getSelected().equals("0")) {
                                    isall = false;
                                }
                            }
                            cb_all.setChecked(isall);
                        }
                        goodAdapter.setList(goods);
                        handle();
                        
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                    }
                });
    }
    
    public void getRecommendGoods(boolean isLoading){
        StoreRequest.recommendGood(page)
                .compose(DoTransform.<RecommendGoodEntity>applyScheduler(this,isLoading))
                .compose(this.<RecommendGoodEntity>bindToLifecycle())
                .subscribe(new HttpSubscriber<RecommendGoodEntity>(this) {
                    @Override
                    protected void onSuccess(RecommendGoodEntity entity) {
                        if(page==1){
                            data.clear();
                        }
                        data.addAll(entity.getGoods());
                        
                        baseAdapter.setList(data);
                        
                        if(page>=entity.getPageCount()){
                            smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }else {
                            smartRefreshLayout.setNoMoreData(false);
                        }
                        
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();
                        
                    }

                    @Override
                    protected void onFail(String msg) {
                        ToastUtil.toastShortNegative(msg);
                        smartRefreshLayout.finishRefresh();
                        smartRefreshLayout.finishLoadMore();
                    }
                });
        
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 1;
        getData(false);
        getRecommendGoods(false);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page = page + 1;
        getRecommendGoods(false);
    }

    @Override
    public void onClick(View view) {
        
    }

    @Override
    public void onEventMainThread(YEventBuses.Event event) {
        super.onEventMainThread(event);
        if(event.is("store_update")){
            page = 1;
            getData(false);
            getRecommendGoods(false);
        }else if(event.is("pay")){
            finish();
        }
    }

    public void handle() {
        boolean flag = true;
        float total = 0;
        jiesuanNum = 0;
        for (int i = 0; i < goods.size(); i++) {
            if (goods.get(i).getSelected().equals("0")) {
                flag = false;
            } else {
                jiesuanNum = jiesuanNum + 1;
                float price = Float.valueOf(goods.get(i).getGoods_price());
                int shuliang = goods.get(i).getGoods_num();
                total = total + price * shuliang;
            }
        }

        if(cb_all.isChecked()&&!flag){
            isCheckAll = false;
        }else {
            isCheckAll = true;
        }
        
        cb_all.setChecked(flag);
        if(isManage){
            tv_jiesuan.setText("结算(" + jiesuanNum + ")");
            tv_totalNum.setText("合计：￥" + total);
        }

    }
    
}
